package com.tongtech.proxy.core.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

public class StringDecryptUtil {
    private static final String[] ALGORITHMS = new String[]{
            "MD5", "SHA-1", "SHA-256", "SHA-384", "SHA-512"
    };

    public static String decrypt(String str, String algorithm) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] bytes = Base64.getDecoder().decode(str);
        byte[] digest = md.digest(bytes);

        // 使用暴力破解方法尝试解密

        for (int i = 0; i < 256; i++) {
            byte[] newBytes = Arrays.copyOf(bytes, bytes.length);
            newBytes[0] = (byte) i;
            if (Arrays.equals(digest, md.digest(newBytes))) {
                return new String(newBytes);
            }
        }

        return null;
    }

    public static String decrypt(String str) throws NoSuchAlgorithmException {
        return decrypt(str, ALGORITHMS[0]);
    }

    public static String decryptAll(String str) throws NoSuchAlgorithmException {
        StringBuilder sb = new StringBuilder();
        for (String algorithm : ALGORITHMS) {
            String decryptedStr = decrypt(str, algorithm);
            if (decryptedStr != null) {
                sb.append(algorithm).append(":").append(decryptedStr).append("\n");
            }
        }
        return sb.toString();
    }
}
